package com.demo.config;



import com.demo.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component//自定义权限不足异常类
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        // 返回 JSON
        response.setContentType("application/json;charset=utf-8");
        // 状态码 403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 写出
        PrintWriter out = response.getWriter();
        String errorMessage = authException.getMessage();
        if (StringUtils.isBlank(errorMessage)) {
            errorMessage = "权限不足!";
        }

        Result result = new Result(HttpServletResponse.SC_FORBIDDEN, "权限不足，无法访问资源", errorMessage);

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
        out.close();
    }
}
